package com.escom.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.androidplot.Plot;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.escom.R;
import com.escom.service.EstudioService;
import com.escom.service.PlotElectroDynamic;
import com.escom.utils.Constantes;

import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Carlos on 19/04/2014.
 */
public class ElectroFragment extends Fragment {

    private SharedPreferences sharedpreferences;
    private String idMedico;
    private String idPaciente;
    private Handler handler;
    private XYPlot dynamicPlot;
    private PlotObservador plotUpdater;

    private class PlotObservador implements Observer {
        Plot plot;

        public PlotObservador(Plot plot) {
            this.plot = plot;
        }

        @Override
        public void update(Observable o, Object arg) {
            plot.redraw();
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View viewActivity = inflater.inflate(R.layout.fragment_electro, container, false);
        sharedpreferences = getActivity().getSharedPreferences(Constantes.MY_PREFERENCES, Context.MODE_PRIVATE);
        idPaciente = sharedpreferences.getString(Constantes.ID_PACIENTE_KEY, null);
        idMedico = sharedpreferences.getString(Constantes.ID_MEDICO_KEY, null);


        dynamicPlot = (XYPlot) viewActivity.findViewById(R.id.dynamicPlot);
        dynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));
        LineAndPointFormatter graphOne = new LineAndPointFormatter(Color.rgb(0, 0, 200), null, null, null);
        //graphOne.getFillPaint().setAlpha(220);
        dynamicPlot.setGridPadding(5, 0, 5, 0);
        dynamicPlot.setRangeBoundaries(0,5, BoundaryMode.FIXED);
        dynamicPlot.setDomainBoundaries(0,30, BoundaryMode.FIXED);

        PlotElectroDynamic threadSeriePlot = new PlotElectroDynamic();
        dynamicPlot.addSeries(threadSeriePlot, graphOne);

        plotUpdater = new PlotObservador(dynamicPlot);

        threadSeriePlot.addObserver(plotUpdater);

        Thread tareaPlot = new Thread(threadSeriePlot);
        tareaPlot.start();


        registerForContextMenu(dynamicPlot);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                int codeResponse = msg.getData().getInt("message");
                Intent intent;
                switch (codeResponse) {
                    case Constantes.EXITO:
                        Toast.makeText(getActivity().getApplicationContext(), "Exito", Toast.LENGTH_SHORT).show();
                        intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        break;
                    case Constantes.ERROR_COMUNICACION:
                        Toast.makeText(getActivity().getApplicationContext(), "Error al actulizar. Intentelo de nuevo", Toast.LENGTH_SHORT).show();
                        intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        };
        return viewActivity;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderIcon(R.drawable.ic_action_about);
        menu.setHeaderTitle("¿Desea finalizar el estudio medico?");
        MenuInflater inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.context_electro, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mnuCtxFinalizarEstudio:
                EstudioService estudioService = new EstudioService( handler, idPaciente, idMedico);
                Thread tareaEstudio = new Thread(estudioService);
                tareaEstudio.start();
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

}
